#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params

set -e

# Note: use lowercase names for the Docker images
DOCKER_IMAGE="azureiotpcs/iothub-manager-dotnet"
# "testing" is the latest dev build, usually matching the code in the "master" branch
DOCKER_TAG="$DOCKER_IMAGE:testing"

# Debug|Release
CONFIGURATION=Release

APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && cd .. && pwd )/"
source "$APP_HOME/scripts/.functions.sh"

compile() {
    check_dependency_dotnet

    cd $APP_HOME
    dotnet restore
    dotnet build --configuration $CONFIGURATION
}

build_docker_image() {
    check_dependency_docker
    check_dependency_git

    cd $APP_HOME

    DOCKER_LABEL2="Commit=$(git log --pretty=format:'%H' -n 1)"
    DOCKER_LABEL3="Date=$(/usr/bin/env date +%Y-%m-%dT%H:%M:%S)"

    rm -fR out/docker
    rm -fR WebService/bin/Docker

    mkdir -p out/docker/webservice

    dotnet publish WebService --configuration $CONFIGURATION --output bin/Docker

    cp -pR WebService/bin/Docker/*       out/docker/webservice/

    cp scripts/docker/.dockerignore              out/docker/
    cp scripts/docker/Dockerfile                 out/docker/
    cp scripts/docker/content/run.sh             out/docker/

    cd out/docker/
    
    docker build --compress --tag $DOCKER_TAG \
        --label "$DOCKER_LABEL2" --label "$DOCKER_LABEL3" .

    echo "Run './scripts/docker/publish' to publish the image to the registry"
}

compile
build_docker_image

set +e
